#include "bluetoothserver.h"

#include <ql2capserver.h>
#include <qbluetoothsocket.h>
#include <qbluetoothlocaldevice.h>

static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c8");

BluetoothServer::BluetoothServer() : l2capServer(0), clientSocket(0) {
}

BluetoothServer::~BluetoothServer() {
    stopServer();
}

void BluetoothServer::startServer() {
    qDebug() << "[BluetoothServer] Starting server...";

    l2capServer = new QL2capServer(this);
    connect(l2capServer, SIGNAL(newConnection()), this, SLOT(clientConnected()));

     if(!l2capServer->listen()) {
         qDebug() << "[BluetoothServer] Server starting... FAIL";
     } else {
         qDebug() << "[BluetoothServer] Server starting... OK";
     }

     serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceRecordHandle, (uint)0x00010010);

     QBluetoothServiceInfo::Sequence classId;
     classId << QVariant::fromValue(QBluetoothUuid(serviceUuid));
     serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);

     serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, tr("Bt Chat Server"));
     serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceDescription,
                              tr("Example bluetooth chat server"));
     serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceProvider, tr("Nokia"));
     serviceInfo.setServiceAvailability(1);

     serviceInfo.setServiceUuid(QBluetoothUuid(serviceUuid));

     serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList,
                              QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup));

     QBluetoothServiceInfo::Sequence protocolDescriptorList;
     QBluetoothServiceInfo::Sequence protocol;
     protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap))
              << QVariant::fromValue(quint16(l2capServer->serverPort()));
     protocolDescriptorList.append(QVariant::fromValue(protocol));
     serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
                              protocolDescriptorList);

     if(serviceInfo.registerService()) {
        qDebug() << "[BluetoothServer] Registering service... OK";
     } else {
        qDebug() << "[BluetoothServer] Registering service... FAIL";
     }

     qDebug() << "[BluetoothServer] Server is listening for connections...";
}

void BluetoothServer::stopServer() {
    qDebug() << "[BluetoothServer] Stopping server...";

    // Unregister service
     serviceInfo.unregisterService();

     // Close sockets
     //qDeleteAll(clientSockets);

     // Close server
     delete l2capServer;
     l2capServer = 0;

     if(clientSocket) {
         clientSocket->deleteLater();
     }
}

void BluetoothServer::clientConnected() {
    QBluetoothSocket *socket = l2capServer->nextPendingConnection();

    if(!socket)
         return;

     connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
     connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
     clientSocket = socket;

     qDebug() << "[BluetoothServer] Client connected...";

     emit socketConnected(clientSocket);
}

void BluetoothServer::clientDisconnected() {
    qDebug() << "[BluetoothServer] Client disconnected...";

    emit socketDisconnected();

    clientSocket = 0;
}

void BluetoothServer::readData() {
    QBluetoothSocket *socket = qobject_cast<QBluetoothSocket *>(sender());

    if (!socket)
        return;

    while (socket->canReadLine()) {
        QByteArray line = socket->readLine().trimmed();
        qDebug() << "[BluetoothServer] Read line: " << line;
        emit messageReceived(line);
    }
}

